---
title: "Example: Parallel Execution | Workflows | Kastrax Docs"
description: Example of using Kastrax to execute multiple independent tasks in parallel within a workflow.
---

import { GithubLink } from "@/components/github-link";

# Parallel Execution with Steps ✅

When building AI applications, you often need to process multiple independent tasks simultaneously to improve efficiency.

## Control Flow Diagram ✅

This example shows how to structure a workflow that executes steps in parallel, with each branch handling its own data flow and dependencies.

Here's the control flow diagram:

<img
  src="/parallel-chains.png"
  alt="Diagram showing workflow with parallel steps"
  width={600}
/>

## Creating the Steps ✅

Let's start by creating the steps and initializing the workflow.

```ts showLineNumbers copy
import { Step, Workflow } from "@kastrax/core/workflows";
import { z } from "zod";

const stepOne = new Step({
  id: "stepOne",
  execute: async ({ context }) => ({
    doubledValue: context.triggerData.inputValue * 2,
  }),
});

const stepTwo = new Step({
  id: "stepTwo",
  execute: async ({ context }) => {
    if (context.steps.stepOne.status !== "success") {
      return { incrementedValue: 0 }
    }

    return { incrementedValue: context.steps.stepOne.output.doubledValue + 1 }
  },
});

const stepThree = new Step({
  id: "stepThree",
  execute: async ({ context }) => ({
    tripledValue: context.triggerData.inputValue * 3,
  }),
});

const stepFour = new Step({
  id: "stepFour",
  execute: async ({ context }) => {
    if (context.steps.stepThree.status !== "success") {
      return { isEven: false }
    }

    return { isEven: context.steps.stepThree.output.tripledValue % 2 === 0 }
  },
});

const myWorkflow = new Workflow({
  name: "my-workflow",
  triggerSchema: z.object({
    inputValue: z.number(),
  }),
});
```

## Chaining and Parallelizing Steps ✅

Now we can add the steps to the workflow. Note the `.then()` method is used to chain the steps, but the `.step()` method is used to add the steps to the workflow.

```ts showLineNumbers copy
myWorkflow
  .step(stepOne)
    .then(stepTwo) // chain one
  .step(stepThree)
    .then(stepFour) // chain two
  .commit();

const { start } = myWorkflow.createRun();

const result = await start({ triggerData: { inputValue: 3 } });
```

<br />
<br />
<hr className="dark:border-[#404040] border-gray-300" />
<br />
<br />
<GithubLink
  link={
    "https://github.com/kastrax-ai/kastrax/blob/main/examples/basics/workflows/workflow-with-parallel-steps"
  }
/>
